package part02;

import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.datastream.WindowedStream;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.windowing.WindowFunction;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

import java.text.SimpleDateFormat;

public class WindowDemo {
    public static void main(String[] args) throws Exception {
        //1，获取flink Stream执行环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        //2，获取数据流
        DataStreamSource<String> data = env.socketTextStream("centos7-3", 9999);
        //3，获取窗口
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy:MM:dd HH:mm:ss.SSS");
        SingleOutputStreamOperator<Tuple2<String, String>> map = data.map(new MapFunction<String, Tuple2<String, String>>() {
            @Override
            public Tuple2<String, String> map(String s) throws Exception {

                long localDate = System.currentTimeMillis();
                String date = sdf.format(localDate);
                return new Tuple2<>(s, date);
            }
        });
        KeyedStream<Tuple2<String, String>, String> keyBy = map.keyBy(value -> value.f0);
        WindowedStream<Tuple2<String, String>, String, TimeWindow> timeWindow = keyBy.timeWindow(Time.seconds(5));
        //4，操作窗口数据
        SingleOutputStreamOperator<String> apply = timeWindow.apply(new WindowFunction<Tuple2<String, String>, String, String, TimeWindow>() {
            @Override
            public void apply(String s, TimeWindow window, Iterable<Tuple2<String, String>> input, Collector<String> out) throws Exception {
                StringBuilder stringBuilder = new StringBuilder();
                for (Tuple2<String, String> next : input) {
                    stringBuilder.append(next.f0).append("..").append(next.f1);
                }
                String data_ = "s:" + s + "..." + "窗口开始时间：" + sdf.format(window.getStart()) + "..." + "窗口结束时间：" + sdf.format(window.getEnd()) + " input:" + stringBuilder;
                out.collect(data_);
            }
        });
        //5，输出窗口数据
        apply.print();
        //6，触发任务执行
        env.execute();
    }
}
